///author: create by SunJH
///时间: 2021/12/16 0016
///邮箱: 965989158@qq.com
///描述: 极光推送的单例工具，用于初始化，接收消息，发送状态栏通知显示，检测是否打开通知

import 'package:flutter_app/stateLearn/click_txt.dart';
import 'package:get/get.dart';
import 'package:janalytics/janalytics.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

import 'log_util.dart';

class JGUtil {
  static JGUtil? _jgUtil;

  static JGUtil get instance => _jgUtil ?? JGUtil._();
  final _jPush = JPush();
  final _jAnalytics = Janalytics();

  JGUtil._() {
    _jgUtil = this;
  }
  Janalytics get getJAnalytics =>_jAnalytics;
  JPush get getJPush =>_jPush;

  initJGPush(String appKey, String channel,
          {bool production = false, bool debug = true}) {
    _jPush.setup(
        appKey: appKey,
        channel: channel,
        production: production,
        debug: debug);
    ///通知事件
    _jPush.addEventHandler(
      onReceiveNotification: (Map<String, dynamic> message) async {
        LogUtil.logI("收到onReceiveNotification消息了: $message");
      },
      onOpenNotification: (Map<String, dynamic> message) async {
        LogUtil.logI("收到onOpenNotification消息了: $message");
      },
      onReceiveMessage: (Map<String, dynamic> message) async {
        LogUtil.logI("收到onReceiveMessage消息了: $message");
      },
    );
    checkNotificationPermission();
  }

  initJGAnalytics(
    String appKey,
    String channel,
  { bool debug = true}
  ){
    _jAnalytics.setup(appKey: appKey, channel: channel);
    _jAnalytics.setDebugMode(debug);
    _jAnalytics.initCrashHandler();///开启崩溃日志收集
  }

  ///检测通知权限是否打开
  checkNotificationPermission(){
    _jPush.isNotificationEnabled().then((bool value) {
      if(!value){
        Get.showSnackbar(GetBar(title: "提示",
          mainButton: ClickTxt(info: "忽略", onPressed: (){
            ///添加判断SnackBar是否打开，防止出错，导致页面被回退
           if(Get.isSnackbarOpen != null && Get.isSnackbarOpen!) {
             Get.back();
           }
          }),
          message: "为了避免错过重要消息，请打开通知权限",
          onTap:(snack){
            _jPush.openSettingsForNotification();
            if(Get.isSnackbarOpen != null && Get.isSnackbarOpen!) {
              Get.back();
            }
          },
          animationDuration: const Duration(milliseconds:500),
        ));
      }
    });
  }
}
